package cn.xyt.server;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.xyt.dto.Message;
import cn.xyt.dto.SystemProperty;
import cn.xyt.service.CmdService;
import cn.xyt.service.MessageService;

/**
 * 接收 消息的 控制 端, 包括 上报的消息 和 命令返回消息
 * @author tomsun
 *
 */
@Service
public class MessageController {
	@Autowired
	private SystemProperty property;
	
	@Resource
	MessageService messageService;
	
	@Resource
	CmdService cmdService;
	
	public static Map<Integer, Object[]> msgid_exe = new HashMap<>();
	{
		try {
			/* 直接 上报数据*/
			
			msgid_exe.put(0xA8, new Object[]{0xA8, //网络任务预消费订单
					MessageService.class.getMethod("post_A8", Message.class)});
			
			msgid_exe.put(0xB6, new Object[]{0xB6, //上报刷卡订单 
					MessageService.class.getMethod("post_B6", Message.class)});
			
			msgid_exe.put(0xC4, new Object[]{0xC4, //上报设备状态 
					MessageService.class.getMethod("post_C4", Message.class)});
			
			
			msgid_exe.put(0xC8, new Object[]{0xC8, //刷卡 任务完成上传消费订单
					MessageService.class.getMethod("post_C8", Message.class)});
			msgid_exe.put(0xC9, new Object[]{0xC9, //网络任务完成上传消费订单
					MessageService.class.getMethod("post_C9", Message.class)});
			
			
			/********************** 服务器cmd 命令返回 处理 关系*****************************/
			Object[] method =  new Object[]{CmdService.class.getMethod("resp_comm_async", Message.class)};

			msgid_exe.put(0xA4, method); // 设置电流
			msgid_exe.put(0xA5, method); // 设置消费标准
			msgid_exe.put(0xA7, method); // 充电任务
			msgid_exe.put(0xD6, method); // 停止充电任务
			msgid_exe.put(0xD7, method); // 重启
			
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		} 
	}
	
	public boolean exec(Message msg) throws Exception{
		byte[] body = msg.getBody();
		//AA 00 00 A1 01 01 0B  // 透传内容 
		int msgid = body[3] & 0xFF;
		Object [] obj = msgid_exe.get(msgid);
		Method me = null;
		if(obj.length == 2){
			/*返回方法调用*/
			me = (Method) obj[1]; 
			/*获取返回 body */
			byte[] resBody = null;
			try{
				resBody =(byte[]) me.invoke(messageService, msg);
			}catch(Exception e){
				messageService.error("exec -->", e);
			}
			
			/*设置返回msgid 返回和 过来的一致*/
//			int rmsgid = (int)obj[0];
//			resBody[3] = (byte) rmsgid;
			
			msg.setBody(resBody);
			return true;
			
		}else{
			// 处理 命令回复消息, 不需要再回复给 设备
			me = (Method) obj[0]; 
			me.invoke(cmdService, msg);
		}
		return false;
		
	}
	

	
}
